<?php

namespace app\controllers;

use Yii;
use app\components\BaseWechatController;
use app\components\Log;
use app\components\Loyalty;
use app\models\Customer;
use app\models\Tenant;
use app\components\Wechat;
use app\modules\admin\models\MemberCard;
use app\models\MemberCardMap;
use yii\web\ServerErrorHttpException;


/**
 * 用于绑定微信原生会员
 */
class MemberBindingController extends BaseWechatController
{
    public $layout = 'jselect';

    // 初始化是配置tenant 信息和个人信息
    // public function init()
    // {
    //     if (!isset($_GET['appid'])) throw new ServerErrorHttpException('no appid');
    //     if (!isset($_GET['openid'])) throw new ServerErrorHttpException('no openid');
    //     $this->setConfig($_GET['appid'], $_GET['openid']);
    // }
    

	function quick_sort($arr) {
	    //先判断是否需要继续进行
	    $length = count($arr);
	    echo $length."<br/>";
	    if($length <= 1) {
	        return $arr;
	    }
	    //如果没有返回，说明数组内的元素个数 多余1个，需要排序
	    //选择一个标尺
	    //选择第一个元素
	    $base_num = $arr[0];
	    //遍历 除了标尺外的所有元素，按照大小关系放入两个数组内
	    //初始化两个数组
	    $left_array = array();//小于标尺的
	    $right_array = array();//大于标尺的
	    for($i=1; $i<$length; $i++) {
	        if($base_num > $arr[$i]) {
	            //放入左边数组
	            $left_array[] = $arr[$i];
	        } else {
	            //放入右边
	            $right_array[] = $arr[$i];
	        }
	    }
	    //再分别对 左边 和 右边的数组进行相同的排序处理方式
	    //递归调用这个函数,并记录结果
	    $left_array = $this->quick_sort($left_array);
	    $right_array = $this->quick_sort($right_array);
	    //合并左边 标尺 右边
	    return array_merge($left_array, array($base_num), $right_array);
     }
    
    public function actionTest2()
    {
    	$re = $this->quick_sort(['1','5','2','7','3']);
    	echo "<pre/>";
    	var_dump($re);die;
    } 
     
	public function actionTest1()
	{
		$array = ['5','4','3','2','1'];
		$array = ['1','3','3','2','1'];
		$a = 0;
		for ($i=0;$i<count($array);$i++){
			for ($j=0;$j<count($array);$j++){
				++$a;
				echo $i."===".$j."<br/>";
				echo $array[$i]."=>".$array[$j]."<br/>";
				if ($array[$i]>$array[$j]){
					$nex = $array[$i];
					$array[$i] = $array[$j];
					$array[$j] = $nex;
// 					$data[$i] = $array[$j]; 
// 					$data[$j] = $array[$i];
// 					echo "<pre/>";
// 					var_dump($array);
// 				}else {
// 					$array[$j] = $array[$i];
				}
// 				echo 1;
			}
		}
		echo "<pre/>";
		echo $a;
		var_dump($array);
	}
    
    public function actionTest()
    {
//     	$number = "100000000";
//     	$number = "10 0000 0000 0000";
    	$number = "1 0000 0000 0000";
    	$number = "100003213500000000005421000";
//     	$data = substr($number,-8,-4);
    	$length = strlen($number);
//     	echo $length;die;
    	$count = $length-4;
//     	$tg = $length;
    	for ($i=1;$i<$length;$i++){
//     		echo $count."<br/>";
    		if ($count > 0){
    			$data[] = substr($number,$count,4);
    		}
    		if ($count > 0 && $count < 4){
//     			echo 1;
    			$data[] = substr($number,0,$count);
    		} elseif ($count >= 0 && $count < 4) {
    			$data[] = substr($number,0,4);
    		}
    		--$count;
    		--$count;
    		--$count;
    		--$count;
    	}
    	//数组交换位置排序ss
    	$end = end($data);
    	$re = array_keys($data,$end);
    	$end_nubmer = $re[0];
    	foreach ($data as $k => $v){
    			$array[] = $data[$end_nubmer];
    		--$end_nubmer;
    	}
//     	$test = $data;
//     	$end = end($data);
//     	$first = $data[0];
//     	$re = array_keys($data,$end);
//     	$test[0] =  $end;
//     	$test[$re[0]] = $first;
    	$testData = implode(".",$array); 
    	echo $testData;
//     	for ($i=$length;$i!=0;$i--){
//     		if ($i % 5 == 0 && $count == 0){
//     			$data[$count] = $i;
//     			++$count;
//     			//     			$data[] = substr($number,$i);
//     		} elseif ($i % 5 == 0 && $count != 0){
//     			//上一次记录的位数
//     			$on_count = $count-1;
//     			//获取上次记录的最后一位来组合下一组截取范围
//     			$data[$count] = substr($data[$on_count],-1).'-'.$i;
//     			++$count;
//     		}
//     	}
//     	for ($i=1;$i<=$length;$i++){
//     		if (explode($number,"-".$i))
//     		if ($i % 4 == 0 && $count == 0){
//     			$data[$count] = $i;
//     			++$count;
// //     			$data[] = substr($number,$i);
//     		} elseif ($i % 4 == 0 && $count != 0){
//     			//上一次记录的位数
//     			$on_count = $count-1;
//     			//获取上次记录的最后一位来组合下一组截取范围
//     			$data[$count] = substr($data[$on_count],-1).'-'.$i;
//     			++$count;
//     		}
//     	}
//     	foreach ($data as $k => $v){
    		
//     		$nex_count = explode('-',$v);
//     		if (count($nex_count) == 2){
//     			$test[] = substr($number,'-'.$nex_count[1],'-'.$nex_count[0]);
//     		}else {
//     			$test[] = substr($number,'0',$nex_count[0]);
//     		}
//     		echo "<pre/>";
//     		var_dump($nex_count);
//     	}
    	echo "<pre/>";
    	var_dump($data);
    }
    
    // 旧会员绑定
    public function actionOldMemberBinding()
    {
        $data = Yii::$app->request->get();
        if (!empty($data['appid'])) {

            $this->setConfig($data['appid'], $data['openid']);

            $code = Wechat::code_decrypt(['encrypt_code' => $data['encrypt_code']]);
            if ($code['errcode'] == 0 && $code['errmsg'] == 'ok') {
                $code = $code['code'];
            } else {
                throw new ServerErrorHttpException('encrypt_code error.');
            }
            $model = new Customer();
            return $this->render(
                'member_binding',
                [
                    'appid' => $data['appid'], 'openid' => $data['openid'],
                    'model' => $model, 'card_id' => $data['card_id'], 'code' => $code,
                ]
            );
        }
    }

    //旧会员激活
    public function actionCustomerSave()
    {
        $data = Yii::$app->request->post();
        Log::debug("Customer-POST-DATA", $data);
        if (!empty($data['mobile'])) {
            // 查询该用户是否存在
            $search_re = Loyalty::customer_search(['mobile' => $data['mobile']]);
            if ($search_re['status'] == 'success') {
                //判断老用户openid是否存在，防止重复更新openid
                $customers = $search_re['result']['customers'];
                $wechat_openid = array_column($customers, 'wechat_openid');
                if (empty($wechat_openid[0])) {
                    $customer = current($search_re['result']['customers']);
                    $datas = [
                        'code' => $customer['code'],
                        'wechat_openid' => $data['openid'],
                    ];
                    $save_re = Loyalty::customer_update($datas);
                    //激活原生会员卡
                    if ($save_re['status'] == 'success') {
                        $re = $this->ActivateMemberCard($data['wechat_code'], (int)$customer['points']);
                        Log::debug("WECHAT-ACTIVATE", $re);
                        if ($re['errmsg'] == "ok") {
                            return json_encode(['status' => 'success', 'msg' => '激活成功']);
                        } else {
                            return json_encode(['status' => 'error', 'msg' => $re['errmsg']]);
                        }
                    }
                } else {
                    return json_encode(['status' => 'error', 'msg' => '您已绑定过了']);
                }
            } else {
                return json_encode(['status' => 'error', 'msg' => '您不是老用户']);
            }
        }
    }

    // 新会员注册
    public function actionNewMember()
    {
    	// http://william.sun.xgate.com/wechat-member-center/web/index.php/member-binding?appid=wxeca2e361be1de14c&openid=o2Rmrtzjjg68MAirKb8XUJ7YdWc0
        $get = Yii::$app->request->get();
        $appid = $get['appid'];
        $openid = $get['openid'];
        $encrypt_code = $get['encrypt_code'];
        $activate_ticket = $get['activate_ticket'];
        Log::debug("create-new-member", $get);
        if (empty($appid) || empty($openid) || empty($encrypt_code) || empty($activate_ticket)) {
            throw new ServerErrorHttpException('invalid request.');
        }

        $this->setConfig($appid, $openid);

        // 请求获取用户填写的资料        
        $info = Wechat::card_temp_userinfo_get(['activate_ticket' => $activate_ticket]);
//         Log::debug('new-member-info', $info);
        if ($info['errmsg'] != 'ok') {
            // 用户填写资料点击提交  后台获取用户资料失败
            throw new ServerErrorHttpException('tmp info lost.');
        }

        $data = $info['info']['common_field_list'];
        $userinfo = array_column($data, 'value', 'name');
// 		Log::debug('Binding',$userinfo);
        // 必填选项
        $username = $userinfo['USER_FORM_INFO_FLAG_NAME'];
        $sex = $userinfo['USER_FORM_INFO_FLAG_SEX'];
        $mobile = $userinfo['USER_FORM_INFO_FLAG_MOBILE'];
        // 非必填
        if (array_key_exists('USER_FORM_INFO_FLAG_EMAIL', $userinfo)) {
        	$email = $userinfo['USER_FORM_INFO_FLAG_EMAIL'];
        } else {
        	$email = '';
        }
        if (array_key_exists('USER_FORM_INFO_FLAG_BIRTHDAY', $userinfo)) {
        	$birthday = $userinfo['USER_FORM_INFO_FLAG_BIRTHDAY'];
        } else {
        	$birthday = '';
        }
        // 解码entrypt_code 获取卡卷code
        $wechatres = Wechat::code_decrypt(['encrypt_code' => $encrypt_code]);
        if ($wechatres['errcode'] == 0 && $wechatres['errmsg'] == 'ok') {
        	$wechat_code = $wechatres['code'];
        } else {
        	// 解码失败 可能原因 encrtypt_code过期 或者appid不正确
        	throw new ServerErrorHttpException('encrypt_code error.');
        }
        // 检查是否为新用户 
        $isNew = true;
//         $init_points = 0;
        $old_member = Loyalty::customer_search(['mobile' => $mobile]);
        if ($old_member['status'] == 'success') {
            // 是老用户更新用户信息,直接激活微信会员卡
            $code_data = current($old_member['result']['customers']);
            $data_loyalty = [
            	'code' => $code_data['code'],
                'wechat_openid' => $openid,
                'last_name' => $username,
            ];
            $old_save = Loyalty::customer_update($data_loyalty); // 在loyalty里绑定openid  
//             $init_points = $code_data['points'];
            //激活微信会员卡
            $wechat_number = $code_data['card_number'];
            $wechat_data = [
// 	            "init_bonus" => 0,
// 	            "init_bonus_record" => "旧积分同步",
	            'membership_number' => $wechat_number,
	            'code' => $wechat_code
            ];
            // 调用微信api 激活用户的会员卡
	        $activate = Wechat::card_activate($wechat_data);
	        if ($activate == "ok"){
	        	$map = MemberCardMap::find()->where(['openid' => $openid, 'cardid' => "p2RmrtxScDyRALt10AGgpKmzaNjk"])->one();
	        	if (!empty($map)){
	        		$map->status = MemberCardMap::STATUS_ACTIVATE;
	        		$map->activate_at = time();
	        		$re = $map->save();
	        	}
	        	Log::debug('map',$re);
	        }
            Log::debug('wechat_number', $wechat_number);
            $isNew = false;
        }
        //新用户
        if ($isNew){
        	//是新用戶跳到隐藏webform页面
        	$data = [
	        	'mobile' => "86".$mobile,
	        	'gender' => $sex,
	       		'wechat_openid' => $openid,
	       		'last_name' => $username,
	       		'wechat_code' => $wechat_code,
        	];
       		// $data = [
	       		// 'mobile' => "8618623836813",
	       		// 'gender' => '男',
	       		// 'wechat_openid' => "o2Rmrt5r5C-axUzpV-Vh2zyDpIQA",
	       		// 'code' => "wxTest001",
	       		// 'last_name' => 'wxTest',
	       		// 'wechat_code' => $wechat_code,
       		//];
        	if ($birthday != ""){
       			$birthdays = explode('-', $birthday);
       			$data['birth_yyyy'] = $birthdays[0];
       			$data['birth_mm'] = $birthdays[1];
       			$data['birth_dd'] = $birthdays[2];
       		}
       		if ($email != ""){
       			$data['email'] = $email;
       		}
        	Log::debug('data',$data);
       		return $this->render('webform1', ['data' => json_encode($data)]);
        }
        //老用户跳转页面
        return $this->render('member_center');  
    }
    

    // 会员卡详情
    public function actionMemberCardInfo()
    {
        return $this->render('membercard');
    }

    // 会员资料
    public function actionMemberProfile()
    {
    	$this->setConfig($_GET['appid'], $_GET['openid']);
    	$re = Loyalty::customer_get(['wechat_openid' => $_GET['openid']]);
    	Log::debug('my user', $re);
    	if ($re['status'] != 'success'){
    		echo "<h1>您还没有激活,请先激活!</h1>";die;
    	}
    	
        if (Yii::$app->request->isPost) {
            $data = Yii::$app->request->post();
            $data = array_filter($data);

            // 其实Loyalty的birthday更新不了是因为没有这个，birthday是由birth_yyyy/birth_mm/birth_dd拼成的
            $birthday = $data['birthday'];
            $y = substr($birthday, 0, 4);
            $m = substr($birthday, 5, 2);
            $d = substr($birthday, 8, 2);
            $data['birth_yyyy'] = $y;
            $data['birth_mm'] = $m;
            $data['birth_dd'] = $d;
            unset($data['_csrf']);
//             unset($data['birthday']);
            Loyalty::customer_update($data);
            $userInfo = Loyalty::customer_get(['code' => $data['code']]);
            $this->setUserInfo($userInfo);
            return $this->render('member_center',['is_update' => 1]);
        }
       
        $userInfo = Loyalty::customer_get(['wechat_openid' => $_GET['openid']]);
        Log::debug('my user', $userInfo);
        return $this->render('profile', ['userInfo' => $userInfo, 'isComplete' => 'true']);
    }
    
    //领取优惠券
    public function actionCoupon()
    {
    	$this->setConfig($_GET['appid'], $_GET['openid']);
    	$userInfo = $this->getUserInfo();
    	$sign = \app\models\ApiTicket::getsignature('p2RmrtxScDyRALt10AGgpKmzaNjk');
    	return $this->render('index',['sign' => $sign,'userInfo' => $userInfo]);
    }


    
    //测试webform
    public function actionWebForm()
    {
    	$data = [
    	'mobile' => "8618623836813",
    	'gender' => '男',
    	'wechat_openid' => "o2Rmrt5U54B4kkWj5YfQ67g3V3xM",
    	'code' => "wxTest001",
    	'last_name' => 'wxTest',
    	'wechat_code' => '123456',
    	];
    	return $this->render('webform1',['data' => json_encode($data)]);
    }
    
    //拿到card_number激活微信会员卡
    public function actionActivation()
    {
    	Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    	$datas = Yii::$app->request->post();
    	$wechat_code = $datas['wechat_code'];
    	$wechat_openid = $datas['wechat_openid'];
    	if (!empty($datas)){
    		$uesrInfo = Loyalty::customer_get(['wechat_openid' => $wechat_openid]);
    		Log::debug('TEST USER',$uesrInfo);
    		if ($uesrInfo['status'] == 'success'){
    			$card_number = $uesrInfo['membership']['card_number'];
    			$wechat_data = [
    			"init_bonus" => 0,
    			"init_bonus_record" => "旧积分同步",
    			'membership_number' => $card_number,
    			'code' => $wechat_code
    			];
    			// 调用微信api 激活用户的会员卡
    			$activate = Wechat::card_activate($wechat_data);
    			Log::debug('card_number', $wechat_code);
    			if ($activate['errmsg'] == 'ok') {
//     			if (true){	
    				//记录会员卡激活
    				$map = MemberCardMap::find()->where(['openid' => $wechat_openid, 'cardid' => "p2RmrtxScDyRALt10AGgpKmzaNjk"])->one();
    				if (!empty($map)){
    					$map->status = MemberCardMap::STATUS_ACTIVATE;
    					$map->activate_at = time();
    					$re = $map->save();
    				}
    				return  ['status' => 'success', 'data' => ['msg' => '激活成功']];
    			} else {
    				return ['status' => 'error', 'data' => ['msg' => '激活失败']];
    			}
    		} else {
    			return ['status' => 'error', 'data' => ['msg' => '用户创建失败']];
    		}
    	}
    }
    
    //优惠券核销
    public function actionRedeem()
    {    	
    	if (Yii::$app->request->isPost && Yii::$app->request->isAjax) {
    		Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    		$datas = Yii::$app->request->post();
    		$re = Loyalty::coupon_redeem(['coupon_code' => $datas['coupon_code'], 'redeem_password' => $datas['redeem_password']]);
    		return $re;
    	} else {
    		exit('Bad Request');
    	}    	
    }
    
//优惠券列表
	public function actionCoupon1()
    {
//     	$userInfo = $this->getUserInfo();
// //     	$userInfo = Loyalty::customer_get(['wechat_openid' => $_GET['openid']]);
//     	Log::debug('my userinfo', $userInfo);
//     	$data = ['code' => $userInfo['membership']['code'],'campaign_id' => '1'];
//     	$re = Loyalty::get_coupon_codes($data);
//     	if ($re['status'] == 'success'){
//     		$coupons = json_encode($re);
//     	}else {
//     		$coupons = "";
//         }

//     	$data = ['code' => '5076276140674605','campaign_id' => '1'];
//     	$coupons = Loyalty::get_coupon_codes($data);
//     	$coupons = json_encode($coupons);
    	
        $data = ['code' => '17713607873','campaign_id' => '1'];
        $re = Loyalty::get_coupon_codes($data);
      
        if ($re['status'] == 'success'){
        	$coupon_codes = $re['coupon_codes'];
//         	foreach ($coupon_codes as $k => $v){
//         		//暂时写死
//         		if ($v['coupon_id'] == 21){
//         			$coupon_codes[$k]['barcode_pattern']['pattern_type'] = "fixed";
//         			$coupon_codes[$k]['barcode_pattern']['fixed_value'] = "DC00101823801";
//         		}else {
//         			$coupon_codes[$k]['barcode_pattern'] = "";
//         		}
//         	}
        	$coupons = json_encode($coupon_codes);
        	//     	$data = ['code' => '5076276140674605','campaign_id' => '1'];
        	//     	$coupons = Loyalty::get_coupon_codes($data);
        	//     	$coupons = json_encode($coupons);
        
        	// 	        $data = ['code' => 'test17','campaign_id' => '1'];
//         	$coupons = Loyalty::get_coupon_codes($data);
//         	$coupon_codes = $coupons['coupon_codes'];
//         	//查找未使用的优惠券list
        		
//         	Log::debug('coupon test', $coupon_codes);
//         	foreach ($coupon_codes as $k => $v){
        
//         		if ($v['status_description'] == 'ISSUED'){
//         			$coupon_ids[] = $v['coupon_id'];
//         			$coupon_datas[] = $v;
//         		} else if ($v['status_description'] == 'USED'){
//         			$coupon_ids[] = "";
//         			$coupon_datas[] = "";
//         		}
//         	}
        	 
//         	//找出有barcode的coupon_id和barcode
//         	if(!empty($coupon_ids) && !empty($coupon_datas)){
//         		foreach ($coupon_ids as $num => $coupon_id){
//         			$re = Loyalty::list_coupon(['coupon_id' => $coupon_id]);
//         			if (!empty($re['coupon_list'][0]['coupon']['barcode_pattern'])){
//         				$barcode_patterns[$num]['coupon_id'] = $re['coupon_list'][0]['coupon_id'];
//         				$barcode_patterns[$num]['barcode_pattern'] = $re['coupon_list'][0]['coupon']['barcode_pattern'];
//         			}
        
//         		}
        		 
//         		foreach ($coupon_datas as $key => $coupon_data){
//         			if (isset($barcode_patterns[$key]['coupon_id'])){
//         				if ($barcode_patterns[$key]['coupon_id'] == $coupon_data['coupon_id']){
//         					$coupon_datas[$key]['barcode_pattern'] =  $barcode_patterns[$key]['barcode_pattern'];
//         				}else {
//         					$coupon_datas[$key]['barcode_pattern'] =  "";
//         				}
//         			}
//         		}
//         		echo 1;die;
//         		$coupons = json_encode($coupon_datas);
//         	}else {
//         		$coupons = json_encode($coupon_codes);
//         	}
        } else {
        	$coupons = "";
        }
        
    	Log::debug('my coupon', $coupons);
        return $this->render('coupon-list'
            , ['coupons' => $coupons, 'userInfo' => $userInfo]
        );
    }

    
    public function actionError()
    {
    	return $this->render('error');
//     	echo "<h2>Coming Soon, 敬请期待</h2>";
    }
}
